const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const cors = require("cors");
const bodyParser = require("body-parser");
const fs = require("fs");
const fse = require("fs-extra");
const FileStreamRotator = require("file-stream-rotator");
const { baseUrl } = require("./config/config.default").route;

const indexRouter = require("./routes/index");
const homeListRouter = require("./routes/home-list");
const detailRouter = require("./routes/detail");
const getStaticRouter = require("./routes/get-static-file");
const getPublicCompressRouter = require("./routes/get-public-compress");
const app = express();

const logDirectory = path.join(__dirname, "logs/request");

fs.existsSync(logDirectory) || fse.ensureDirSync(logDirectory);

const accessLogStream = FileStreamRotator.getStream({
	date_format: "YYYYMMDD",
	filename: path.join(logDirectory, "access-%DATE%.log"),
	frequency: "daily",
	verbose: false
});

app.use(logger("combined", { stream: accessLogStream }));
app.use(express.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
//开启跨域
app.use(cors());
//解析请求
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(`${baseUrl}/index`, indexRouter);
app.use(`${baseUrl}/home-list`, homeListRouter);
app.use(`${baseUrl}/detail`, detailRouter);
app.use(`${baseUrl}/download/static`, getStaticRouter);
app.use(`${baseUrl}/download/compress`, getPublicCompressRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
	next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
	// set locals, only providing error in development
	res.locals.message = err.message;
	res.locals.error = req.app.get("env") === "development" ? err : {};

	// render the error page
	res.status(err.status || 500);
	res.send("this is xinxin-article-image server");
});

module.exports = app;
